﻿using System;
using System.Collections.ObjectModel;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Extentions;
using Pyramid.Models;
using System.Data.Entity;

namespace Pyramid.Controllers
{
	public class StaffSalarySetController : BaseController
	{
		public ActionResult List()
		{
			return View();
		}

		/// <summary>
		/// 给员工调薪
		/// </summary>
		/// <param name="id">员工ID</param>
		public ActionResult Create(int id)
		{
			//所有工资组成部分
			ViewBag.SalaryParts = Db.SalaryParts.ToList();
			//最后一次工资设定
			ViewBag.LastSet = Db.StaffSalarySetMasters
				.Include(x => x.StaffSalarySetDetails)
				.OrderByDescending(x => x.CreateTime)
				.FirstOrDefault(x => x.StaffId == id);
			ViewBag.StaffId = id;
			return View();
		}

		[HttpPost]
		public ActionResult Create(FormCollection formCollection)
		{
			var staffId = Convert.ToInt32(formCollection["staffId"]);

			var effectiveDate = DateTime.Parse(formCollection["effectiveDate"]);
			var last = Db.StaffSalarySetMasters
				.FirstOrDefault(x => x.StaffId == staffId && SqlFunctions.DateDiff("m", x.EffectiveDate, effectiveDate) == 0);
			if (last != null)
			{
				return JError(string.Format("{0:yyyy年M月}做过工资调整，请重新选择生效日期！", effectiveDate));
			}

			var remark = formCollection["remark"];

			var master = new StaffSalarySetMaster
			{
				StaffId = staffId,
				CreateTime = DateTime.Now,
				CreateUserId = User.UserId,
				EditTime = DateTime.Now,
				EffectiveDate = effectiveDate,
				StaffSalarySetDetails = new Collection<StaffSalarySetDetail>(),
				Remark = remark
			};

			var salaryParts = Db.SalaryParts.ToList();
			var keys = formCollection.AllKeys.Where(x => x.StartsWith("part_")).ToList();
			foreach (var key in keys)
			{
				var value = Convert.ToDecimal(formCollection[key]);
				var id = Convert.ToInt32(key.Substring("part_".Length));
				if (value > 0 && salaryParts.Any(x => x.Id == id))
				{
					master.StaffSalarySetDetails.Add(new StaffSalarySetDetail { PartId = id, Value = value });
				}
			}

			if (master.StaffSalarySetDetails.Count == 0)
			{
				return JError("工资参数不能全为空，或全小于0！");
			}

			Db.StaffSalarySetMasters.Add(master);
			Db.SaveChanges();

			return JSuccess("操作成功！", "tab_sal_salaryset");
		}

		/// <summary>
		/// 获取员工调薪统计信息
		/// </summary>
		public ActionResult Master(string keywords, KendoRequestModel model)
		{
			var query =
				Db.Staves.Include(x => x.StaffSalarySetMasters).Include(x => x.Department).Include(x => x.Position).AsQueryable();
			if (!string.IsNullOrWhiteSpace(keywords))
			{
				query = query.Where(x => x.Code.Contains(keywords) || x.FullName.Contains(keywords));
			}
			var data = query
				.OrderBy(x => x.CreateTime)
				.Skip(model.Skip)
				.Take(model.Take)
				.ToList()
				.Select(x => new StaffSalarySetMasterInfo
				{
					StaffId = x.Id,
					StaffCode = x.Code,
					Gender = x.GenderEnum.ToDescription(),
					Department = x.Department.Name,
					EntryDate = x.EntryDate.ToString("yyyy-MM-dd"),
					Position = x.Position.Name,
					FullName = x.FullName,
					Status = x.StatusEnum.ToDescription(),
					SalarySetTimes = x.StaffSalarySetMasters.Count
				});
			return JNormal(new KendoResponseModel { Total = query.Count(), Data = data });
		}

		/// <summary>
		/// 获取员工的调薪明细
		/// </summary>
		public ActionResult Detail(int staffId)
		{
			var data = Db.StaffSalarySetMasters
				.Include(x => x.StaffSalarySetDetails.Select(y => y.SalaryPart))
				.Where(x => x.StaffId == staffId)
				.ToList();
			var result = (from master in data
						  from detail in master.StaffSalarySetDetails
						  select new StaffSalarySetDetailInfo
						  {
							  EffectiveDate = master.EffectiveDate.ToString("yyyy年M月"),
							  VariableName = detail.SalaryPart.VariableName,
							  Value = detail.Value.ToString(detail.SalaryPart.DisplayFormat),
							  PartRemark = detail.SalaryPart.Remark
						  }).ToList();
			return JNormal(result);
		}
	}
}